<?php

namespace common\models\app;

use Yii;
use common\helpers\IpHelper;

/**
 * This is the model class for table "{{%app_token}}".
 *
 * @property int $id
 * @property int $client_id 客户端应用ID
 * @property int $device_id 设备ID
 * @property string|null $access_token AccessToken
 * @property int $expired_at 过期时间
 * @property int $user_id 用户ID
 * @property int $version_id 版本ID
 * @property string|null $scope 授权范围
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class AppToken extends \common\db\ActiveRecord {

    /**
     * Token过期时间 2小时
     */
    const TOKEN_EXPIRED = 7200;
    //
    const OS_MP = 'mp';
    const OS_ANDROID = 'android';
    const OS_IOS = 'ios';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%app_token}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['client_id', 'device_id', 'expired_at', 'user_id', 'version_id', 'created_at', 'updated_at'], 'integer'],
            [['access_token', 'scope'], 'string', 'max' => 64],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'client_id' => '客户端应用ID',
            'device_id' => '设备ID',
            'access_token' => 'AccessToken',
            'expired_at' => '过期时间',
            'user_id' => '用户ID',
            'version_id' => '版本ID',
            'scope' => '授权范围',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function generateAccessToken() {
        $this->access_token = Yii::$app->security->generateRandomString();
        $this->expired_at = time() + self::TOKEN_EXPIRED;
    }

    /**
     * 通过Token登录
     * 这个就是我们进行yii\filters\auth\QueryParamAuth调用认证的函数，下面会说到
     * @param type $accessToken
     * @param type $type
     * @return type
     */
    public static function loginByAccessToken($accessToken, $type) {
        $token = Yii::$app->security->decryptDataByKey($accessToken);
        if ($token === false) {
            return null;
        }
        $query = static::find()->andWhere([
            'access_token' => $token]
        );
        if (!YII_DEBUG) {
            $query->andWhere(['>', 'expired_at', time()]);
        } else {
            $query->andWhere([
                'or',
                ['expired_at' => 0],
                ['>', 'expired_at', time()]
            ]);
        }
        $query->debug();
        return $query->one();
    }

    public function getUser() {
        $identityClass = Yii::$app->user->identityClass;
        return $this->hasOne($identityClass, ['id' => 'user_id'])->andWhere([
            'status' => $identityClass::STATUS_ACTIVE
        ]);
    }

    public function getDevice() {
        return $this->hasOne(AppDevice::class, ['id' => 'device_id']);
    }

    public function getVersion() {
        return $this->hasOne(AppVersion::class, ['id' => 'version_id']);
    }

    public function getBuild() {
        return $this->version ? $this->version->build : 0;
    }

    /**
     * 绑定新登录的用户到当前Token
     * @param integer $userid
     * @return type
     */
    public function bindUser($userid) {
        //访问记录
        $accessLog = AppAccessLog::findOrNew([
            'user_id' => $userid,
            'device_id' => $this->device_id,
            'token_id' => $this->id,
            'ip' => IpHelper::ip(),
        ]);
        $accessLog->save(false);

        //TOKEN解绑
        if (Yii::$app->id !== 'app-mpend') {
            static::updateAll(['user_id' => 0], ['user_id' => $userid]);
        }
        //TOKEN新绑定
        $this->setOldAttribute('user_id', 0);
        $this->user_id = $userid;
        return $this->save();
    }

    public function getDebug() {
        return [
            'encrypt_token' => Yii::$app->security->encryptDataByKey($this->access_token)
        ];
    }

    public function fields() {
        $fields = [
            'access_token',
            'expired_at',
        ];
        if (YII_DEBUG) {
            $fields['_debug'] = 'debug';
        }
        return $fields;
    }

}
